<template>
  <div>
    <div class="common-layout">
      <el-container>
        <el-header>
          当前登录人：{{ useStore.userinfo.name }}
          <el-button type="primary" @click="logout">退出登录</el-button>
        </el-header>
        <el-container>
          <el-aside width="200px">
            <el-menu
              active-text-color="#ffd04b"
              background-color="#545c64"
              class="el-menu-vertical-demo"
              default-active="2"
              text-color="#fff"
              @open="handleOpen"
              @close="handleClose"
              router
            >
              <el-sub-menu index="1">
                <template #title>
                  <el-icon>
                    <location />
                  </el-icon>
                  <span>用户管理</span>
                </template>
                <div v-for="(item, index) in permissiondata" :key="index">
                  <DynamicMenu :item="item" />
                </div>
                <el-menu-item index="1-1">测试页面</el-menu-item>
              </el-sub-menu>
            </el-menu>

            <!-- <el-menu active-text-color="#ffd04b" background-color="#545c64" class="el-menu-vertical-demo"
                          default-active="2" text-color="#fff" @open="handleOpen" @close="handleClose" router>
                          <el-sub-menu index="1">
                              <template #title>
                                  <el-icon>
                                      <location />
                                  </el-icon>
                                  <span>用户管理</span>
                              </template>
                              <template v-for="item in permission" :key="item.ProfessionId">
                                  <el-sub-menu v-if="item.children.length > 0" :index="item.path">
                                      <template #title>
                                          <el-icon>
                                              <location />
                                          </el-icon>
                                          <span>{{ item.professionName }}</span>
                                      </template>
                                      <DynamicMenu :items="item.children" />
                                  </el-sub-menu>
                                  <el-menu-item v-else :index="item.path" @click="navigate(item.path)">
                                      {{ item.professionName }}
                                  </el-menu-item>
                              </template>
                              <el-menu-item index="1-1">测试页面</el-menu-item>
                          </el-sub-menu>
                      </el-menu> -->
          </el-aside>
          <el-main>
            <RouterView></RouterView>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
//@ts-ignore
import Cookies from 'js-cookie';
import { useCounterStore } from '@/stores/counter';
import { useRouter, type RouteRecordRaw } from 'vue-router';
import DynamicMenu from '../components/DynamicMenu.vue'; //导入递归菜单组件
import axiosInstance from "@/stores/Utils/axiosHelp"

const useStore = useCounterStore();
const router = useRouter();

const handleOpen = (key: string, keyPath: string[]) => {
  router.push({ name: keyPath[1] });
  console.log(key, keyPath); //Test  ['1', 'Test']
};
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

interface Permission {
  id: 1,
  name: string
  description: string
  parentId: number
  path: string,
  component: string,
  redirect: string,
  Children: Permission[];
}

const permissiondata = ref<Permission[]>([]);

//退出登录
const logout = () => {
  router.push('/');
};

onMounted(() => {
  getTreePermission();
});

//获取权限树
const getTreePermission = () => {
  axiosInstance.get('/api/Jurisdiction/GetTreePermission').then(async (r) => {
    permissiondata.value = r.data;
    console.log(permissiondata.value);
    await addDynamicRoutes(permissiondata.value);
  });
};

//添加动态路由的函数
const addDynamicRoutes = async (permissions: Permission[]) => {
  await permissions.forEach((permissionInfo) => {
    console.log(permissionInfo);
    //创建动态路由
    const route: RouteRecordRaw = {
      path: permissionInfo.path,
      name: permissionInfo.redirect,
      component: () => import(`../views/RBAC/${permissionInfo.component}.vue`),
      children: permissionInfo.Children
        ? permissionInfo.Children.map((child) => ({
            path: child.path,
            name: child.redirect,
            component: () => import(`../views/RBAC/${child.component}.vue`)
          }))
        : [] //如果有子路由，递归生成子路由
    };
    console.log(`../views/RBAC/${permissionInfo.component}.vue`); //获取当前路由配置
    const routes = router.options.routes;
    //找到父路由 MenuView
    const menuViewRoute = routes.find((route) => route.name === 'MenuView');
    //确保 menuViewRoute 存在
    if (menuViewRoute) {
      menuViewRoute.children?.push(route);
      console.log(route);
      router.addRoute(menuViewRoute);
    } else {
      console.error('父路由 MenuView 未找到，无法添加子路由');
    }
  });

  // 重新加载当前路由，确保新路由生成
  router.replace(router.currentRoute.value.path);
  console.log(router.getRoutes());
};
</script>
